package com.zhentao.service.impl;

import com.alibaba.fastjson.JSON;
import com.zhentao.api.schedule.ScheduleClientApi;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.schedule.dto.TaskDto;
import com.zhentao.model.wemedia.pojo.WmNews;
import com.zhentao.service.WmNewsAutoScanService;
import com.zhentao.service.WmNewsTaskService;
import lombok.SneakyThrows;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class WmNewsTaskServiceImpl implements WmNewsTaskService {
    @Autowired
    private ScheduleClientApi scheduleClientApi;

    @Override
    public void addNewsToTask(WmNews wmNews) {
        System.out.println("添加任务到延迟任务里面");
        TaskDto taskDto = new TaskDto();
        taskDto.setTaskType(1);
        taskDto.setPriority(1);
        taskDto.setExecuteTime(wmNews.getPublishTime().getTime());
        taskDto.setParameters(JSON.toJSONBytes(wmNews));
        scheduleClientApi.addTask(taskDto);
    }

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    //每秒钟执行一次
    @Scheduled(fixedRate = 1000)
    @SneakyThrows
    @Override
    public void scanNewsByTask() {
        ResponseResult result = scheduleClientApi.poll(1, 1);
//        System.out.println("获取到redis里面的数据" + result);

        if (result.getCode() == 200 && result.getData() != null) {
            String dataJson = JSON.toJSONString(result.getData());
            TaskDto taskDto = JSON.parseObject(dataJson, TaskDto.class);
            WmNews wmNews = JSON.parseObject(taskDto.getParameters(), WmNews.class);
            System.out.println("获取到对象" + wmNews);

            try {
                // 执行自动审核
                wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
                // 处理完后，可以考虑在这里将任务从队列中移除
            } catch (Exception e) {
                // 捕获异常并打印
                System.err.println("任务处理异常: " + e.getMessage());
            }
        }
    }
}
